package com.sunshine.lnuplus.ui.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager.widget.ViewPager
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.adapter.ChooseWeekRecyclerAdapter
import com.sunshine.lnuplus.base.BaseFragment
import com.sunshine.lnuplus.callback.ChooseWeekCallBack
import com.sunshine.lnuplus.callback.LoadTitleCallBack
import com.sunshine.lnuplus.internet.LoadTitle
import com.sunshine.lnuplus.model.InitData
import com.sunshine.lnuplus.ui.activity.MainActivity
import com.sunshine.lnuplus.ui.activity.TimetableSettingActivity
import com.sunshine.lnuplus.utils.DateUtils
import com.sunshine.lnuplus.utils.TagHelper
import com.sunshine.lnuplus.view.ChooseWeekDialog
import com.sunshine.lnuplus.viewModel.TimetableFragmentViewModel
import kotlinx.android.synthetic.main.fragment_timetable.*

class TimetableFragment : BaseFragment() {

    private lateinit var myActivity: MainActivity
    private lateinit var viewModel: TimetableFragmentViewModel
    private var thisWeek = DateUtils.getThisWeek(InitData.lessonStyle.startMonth, InitData.lessonStyle.startDay)
    private var conn: ServiceConnection? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_timetable, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        myActivity = activity as MainActivity
        viewModel = ViewModelProvider(this).get(TimetableFragmentViewModel::class.java)
        if(savedInstanceState != null){
            thisWeek = savedInstanceState.getInt("this_week")
        }
        initView()
    }

    private fun initView() {
        val lessonStyle = InitData.lessonStyle
        if(getTimetableTheme() == 1 && !viewModel.isNight()){
            lessonStyle.dateAndTimeTextColor = "#000000"
            button_choose_weeks.setTextColor(Color.BLACK)
            timetable_toolbar_text.setTextColor(Color.BLACK)
            imageView_setting.setImageDrawable(resources.getDrawable(R.drawable.ic_settings_black))
        }else{
            lessonStyle.dateAndTimeTextColor = viewModel.getDateAndTimeTextColor()
        }
        viewpager_timetable.apply {
            adapter = ChooseWeekRecyclerAdapter(childFragmentManager, this@TimetableFragment)
            currentItem = thisWeek - 1
            addOnPageChangeListener(object: ViewPager.OnPageChangeListener{
                override fun onPageScrollStateChanged(state: Int) {

                }

                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {

                }

                override fun onPageSelected(position: Int) {
                    thisWeek = position + 1
                    button_choose_weeks.text = "第${thisWeek}周"
                }

            })
        }
        myActivity.setTimetableAdapter(viewpager_timetable.adapter as ChooseWeekRecyclerAdapter)
        initChooseWeek()
        initTitle()
        imageView_setting.setOnClickListener {
            startActivityForResult(Intent(activity, TimetableSettingActivity::class.java), TagHelper.TIMETABLE)
        }
    }

    private fun initChooseWeek() {
        button_choose_weeks.text = "第${thisWeek}周"
        button_choose_weeks.setOnClickListener {
            val chooseWeekDialog = ChooseWeekDialog.newInstance(thisWeek, object : ChooseWeekCallBack{
                override fun onPress(week: Int) {
                    thisWeek = week + 1
                    button_choose_weeks.text = "第${thisWeek}周"
                    viewpager_timetable.currentItem = thisWeek - 1
                }

            })
            chooseWeekDialog.show(childFragmentManager, "choose_week")
        }
        button_choose_weeks.setOnLongClickListener {
            thisWeek = DateUtils.getThisWeek(InitData.lessonStyle.startMonth, InitData.lessonStyle.startDay)
            button_choose_weeks.text = "第${thisWeek}周"
            viewpager_timetable.currentItem = thisWeek - 1
            true
        }
    }



    private fun initTitle(){
        //防止多次加载
        if(InitData.loadTitle.isNullOrEmpty()){
            LoadTitle(object : LoadTitleCallBack{
                override fun onSuccess(title: String) {
                    val message = Message()
                    message.obj = title
                    message.what = 2
                    InitData.loadTitle = title
                    handler.sendMessage(message)
                }
            })
        } else {
            timetable_toolbar_text.text = InitData.loadTitle
        }

    }

    override fun setContent(): Int {
        return R.layout.fragment_timetable
    }

    @SuppressLint("HandlerLeak")
    val handler = object : Handler(){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg.what){
                2 -> {
                    timetable_toolbar_text.text = msg.obj.toString()
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == TagHelper.TIMETABLE){
            when(resultCode){
                Activity.RESULT_OK, TagHelper.TIMETABLESETTING -> viewpager_timetable.adapter?.notifyDataSetChanged()
            }
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("this_week", thisWeek)
    }

    override fun onDestroy() {
        super.onDestroy()
        if(conn != null){
            try {
                activity?.unbindService(conn!!)
            }catch (e: Exception){}

        }
    }

}
